package Server;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

/**
 * Connection of Server with client
 *
 */
public class ClientConnection extends Thread {

	private Server server;
	private Socket connection;
	private BufferedReader inFromClient;
	private String clientNickname;
	private DataOutputStream outToServer;
	
	public ClientConnection(Server server, Socket socket) throws IOException {
		this.server = server;
		this.connection = socket;
		this.inFromClient = new BufferedReader(new InputStreamReader(this.connection.getInputStream()));
		this.outToServer = new DataOutputStream(this.connection.getOutputStream());
	}
	
	public void close() throws IOException {
		this.outToServer.writeBytes("EXIT\n");
		//this.outToServer.close();
	}
	
	public String toString() {
		return this.clientNickname;
	}
	
	public void run() {
		try {
			this.server.addClient(this);
			String message = "";
			this.clientNickname = inFromClient.readLine();
			sendToAll(outToServer, " entrou no chat!");
			sendClients();
			message = inFromClient.readLine();
			while (!message.equals("EXIT")) {
				sendToAll(outToServer, " disse: " + message);
				message = inFromClient.readLine();
			}

			this.server.removeClient(this);
			sendToAll(outToServer, " saiu do chat!");
			sendClients();
			this.connection.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	void sendToAll(DataOutputStream source, String message) throws IOException {
		message += "\n";
		server.log(this.connection.getInetAddress() + message);
		for (ClientConnection client : server.getClients()) {
			if (client.outToServer != source) {
				client.outToServer.writeBytes(this.clientNickname + message);
			}
		}
	}
	void sendClients() throws IOException {
		for (ClientConnection client : server.getClients()) {
			client.outToServer.writeBytes("clientList" + "\n");
			client.outToServer.writeBytes(this.server.getClientList(client) + "\n");
		}
	}
	
	void send(DataOutputStream source, String message, ClientConnection client) throws IOException {
		message += "\n";
		server.log(this.clientNickname + message);
		if (client.outToServer != source) {
			client.outToServer.writeBytes(this.clientNickname + message);
		}
	}
	
}
